#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    tag = false;
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionNew_triggered()
{
    if(!tag)
    {
        tab = new QTabWidget(this);
        tab->setTabsClosable(true);
        ui->gridLayout->addWidget(tab);

        connect(tab, SIGNAL(tabCloseRequest(int)), this, SLOT(removeSubTab(int)));
        tag = true;
    }
    //add to tab widget
    QTextEdit* text = new QTextEdit(this);
    tab->addTab(text, "New File");
}

void MainWindow::on_actionOpen_triggered()
{
    //new tab
    if(!tag)
    {
        tab = new QTabWidget(this);
        tab->setTabsClosable(true);
        ui->gridLayout->addWidget(tab);

        connect(tab, SIGNAL(tabCloseRequest(int)), this, SLOT(removeSubTab(int)));
        tag = true;
    }
    //add to tab widget
    QTextEdit* text = new QTextEdit(this);

    //open file & read
    QString path = QFileDialog::getOpenFileName(this, "Open File...", ".", "Text Files(*.txt);;Sourcecode File(*.cpp);;Header File(*.h)");
    if(path.length()==0)
    {
        QMessageBox::information(NULL, "Open File Error", "You didn't select any files!");
        return;
    }
    //text->setText("");
    QFile file(path);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray str = file.readAll();
        text->setText(str);
    }
    file.close();
    tab->addTab(text, path);
    tab->setCurrentWidget(text);
}

void MainWindow::on_actionSave_triggered()
{
    QString str = tab->tabText(tab->currentIndex());
    QString path;
    if(str == "New File")
    {
        path =QFileDialog::getSaveFileName(this, "Open File...", "/Users/", "Text Files(*.txt);;Sourcecode File(*.cpp);;Header File(*.h)");
        if(path.length()==0)
        {
            QMessageBox::information(NULL, "Open File Error", "你没有选中任何文件！");
            return;
        }
    }
    else
    {
        path = str;
    }
    //to do : write a file
    QFile file(path);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextEdit* temp = (QTextEdit*)(tab->currentWidget());

        //text->toPlainText();
        file.write(temp->toPlainText().toUtf8());
    }
    file.close();
}





